from datetime import datetime, timedelta, timezone
import hashlib
from typing import Union
import time


def _g_time_ms():
    try:
        # 获取当前 UTC 时间，并转换为带时区信息的 datetime 对象
        current_time = datetime.now(timezone.utc)
        # 将 datetime 对象转换为时间戳，并乘以 1000 获得毫秒值
        timestamp_ms = int(current_time.timestamp() * 1000)
        return timestamp_ms
    except Exception as e:
        print(f"Error occurred while getting current time: {e}")
        return 0

class Utils:

    @classmethod
    def time_ms(cls) -> int:
        return _g_time_ms()
    
    @classmethod
    def hash_id(cls, id: Union[int, float, str], len = 4) -> str:
        """返回md5后的前N个字符

        Args:
            id (Union[int, str]): 待MD5的值
            len (int, optional): 返回字符串的长度, 0返回完整的. Defaults to 4.

        Returns:
            _type_: md5后的字符串
        """
        md5 = hashlib.md5(str(id).encode('utf-8')).hexdigest()
        if len > 0:
            return md5[:len]
        else:
            return md5

    @classmethod
    def bucket_id(cls, ms: int = _g_time_ms(),num_buckets = 16) -> int:
        """毫秒级别将时间戳分桶

        Args:
            ms (float, optional): 目标时间戳. Defaults to utc0.
            num_buckets (int, optional): 目标分桶数. Defaults to 16.

        Returns:
            _type_: 分桶id
        """
        num_buckets = 16
        # 获取当前时间戳（毫秒级别）
        if ms == 0:
            ms = cls.time_ms()
        # 计算分桶ID
        bucket_id = ms % num_buckets
        return bucket_id